$(function() {
  //work\启动音乐
  musicModel.init();

  // 初始化页面swiper
  pageScroll.init();

  var preload = new createjs.LoadQueue(false);

  // 获取页面中的图片
  var manifest = [];

  $('img').each(function(i, ele) {
    manifest.push({
      src: $(ele).attr('src')
    })
  });

  // console.log(manifest);

  preload.addEventListener("progress", handleProgress);
  preload.addEventListener("complete", handleComplete);
  // preload.addEventListener("fileload", handleFileLoad);

  preload.loadManifest(manifest);

  function handleProgress(e) {
    e.progress = Math.round(e.progress * 100);
    console.log(e.progress);
    $('.suwis-loading-bar .d-progress').css({
      'width': e.progress - 2 + '%'
    });
    $('.suwis-loading-bar .d-count').html(e.progress + '%');
  }

  function handleComplete(e) {
    // alert('加载完成！');
    // console.log(e);
    $('.suwis-loading').fadeOut(function() {
      $('.suwis-loading').remove();
    })
  }

  function init() {
    //初始化页面模型
    for (var f in window.pageModel) {
      window.pageModel[f].init();
    }
    //检测苹果4
    if ($(window).width() / $(window).height() > 0.7) {
      $(".suwis-page-swiper").addClass('d-mini');
    }
  };
  init();

  $(window).resize(function() {
    if ($(window).width() > $(window).height()) {
      $('#suwis_screentype').show();
    } else {
      $('#suwis_screentype').hide();
    }
  });
  $(window).trigger('resize');
})

/*=====================检测动画状态======================*/
var animationend = "webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend";
/*=====================音乐播放器======================*/
var musicModel = {
  init: function() {
    this.player = $("#suwis_music_player")[0];
    this.$musicIcon = $(".suwis-music-icon");
    var self = this;
    var isplay = false;
    setTimeout(function() {
      self.player.play();
    }, 0);
    $(this.player).on("canplay", function() {
      //音乐播放开始启动音乐图标
      self.$musicIcon.addClass('d-show').on(animationend, function() {
        self.$musicIcon.addClass('d-run');
      });
      isplay = true;
    });

    wx.config({
      // 配置信息, 即使不正确也能使用 wx.ready
      debug: false,
      appId: '',
      timestamp: 1,
      nonceStr: '',
      signature: '',
      jsApiList: []
    });
    wx.ready(function() {
      self.player.play();
    });

    self.$musicIcon.on("click", function(event) {
      if (isplay) {
        isplay = false;
        self.player.pause();
        self.$musicIcon.addClass('d-paused');
      } else {
        isplay = true;
        self.player.play();
        self.$musicIcon.removeClass('d-paused');
      }
    });
  },
  stop: function() {
    //关闭音乐
    this.player.pause();
  },
  play: function() {
    //开启音乐
    this.player.play();
  }
}


//页面滚动模块
//======================================================
var pageScroll = {
  init: function() {
    var togglePlayer = $('#suwis_music_engine')[0];
    this.swiper = new Swiper("#suwis_page_swiper", {
      direction: 'vertical',
      speed: 800,
      effect: 'flip',
      flip: {
        slideShadows: true,
        limitRotation: true,
      },
      onSlideChangeStart: function() {
        // 播放翻页声音
        togglePlayer.play();
      },
      onSlideChangeEnd: function(swiper) {
        //执行当前模块的enter方法
        var activeIndex = swiper.activeIndex;
        var curpage = window.pageModel[$(swiper.slides[activeIndex]).data("flag")];
        try {

          if (typeof curpage != undefined && typeof curpage.enter == "function") {
            curpage.enter();
          }
          //如果当前活动的页面不是第一屏的话就获取活动屏的前一屏
          if (activeIndex > 0) {
            var prevpage = window.pageModel[$(swiper.slides[activeIndex - 1]).data("flag")];
            if (typeof prevpage != undefined && typeof prevpage.leave == "function") {
              prevpage.leave();
            }
          }
          //如果当前活动的页面不是最后一屏的话就获取活动屏的下一屏
          if (activeIndex < swiper.slides.length - 1) {
            var nextpage = window.pageModel[$(swiper.slides[activeIndex + 1]).data("flag")];
            if (typeof nextpage != undefined && typeof nextpage.leave == "function") {
              nextpage.leave();
            }
          }
          //判断是不是第一屏和最后一屏
          if (swiper.isEnd) {
            //$(".suwis-drop-arrow").addClass('d-return');
          } else {
            //$(".suwis-drop-arrow").removeClass('d-return');
          }
          //设置hash
          window.location.hash = $(swiper.slides[activeIndex]).data("flag");
        } catch (e) {
          console.log(e.massage);
        }
      }
    });
  }
}

/*页面模块*/
pageModel = {};

//welcome
//======================================================
pageModel.welcome = {
  init: function() {
    var _this = this;

  },
  enter: function() {
    var _this = this;

  },
  leave: function() {
    var _this = this;

  }
};

pageModel.sixing = {
  init: function() {
    var _this = this;

  },
  enter: function() {
    var _this = this;
    $('.suwis-drop-arrow').fadeIn();
  },
  leave: function() {
    var _this = this;

  }
};

pageModel.end = {
  init: function() {
    var _this = this;
    this.music = $('#suwis_music_engine')[0];
    this.music.onended = function() {
      setTimeout(function() {
        musicModel.play();
      });
    };
  },
  enter: function() {
    var _this = this;
    // this.music.play();
    // musicModel.stop();
    $('.suwis-drop-arrow').fadeOut();
  },
  leave: function() {
    var _this = this;
  }
};



/*重力感应*/
if (window.DeviceOrientationEvent) {
  window.addEventListener("deviceorientation", deviceorientation, false);
}

function deviceorientation(evt) {
  //console.log(event.alpha, event.beta, event.gamma);
  //console.log('重力传感器在动:', evt);
  if (!evt.gamma && !evt.beta) {
    evt.gamma = (evt.x * (180 / Math.PI)); //转换成角度值,
    evt.beta = (evt.y * (180 / Math.PI)); //转换成角度值
    evt.alpha = (evt.z * (180 / Math.PI)); //转换成角度值
  }

  var gamma = evt.gamma
  var beta = evt.beta
  var alpha = evt.alpha

  if (evt.accelerationIncludingGravity) {
    gamma = event.accelerationIncludingGravity.x * 10;
    beta = -event.accelerationIncludingGravity.y * 10;
    alpha = event.accelerationIncludingGravity.z * 10;
  }

  try {
    gamma = gamma.toFixed(1);
    beta = beta.toFixed(1);
    alpha = alpha.toFixed(1);
  } catch (e) {}

  if (this._lastGamma != gamma || this._lastBeta != beta) {
    var tempGX = 0;
    var tempGY = 0;
    tempGX = gamma / 180 * 120;
    tempGY = beta / 180 * 120;
    var param = {
      x: 0,
      y: 0
    }
    if ((-100 + tempGX) >= -200 && (-100 + tempGX) <= 0) {
      param.x = tempGX;
    }
    if ((-100 + tempGY) >= -200 && (-100 + tempGY) <= 0) {
      param.y = tempGY;
    }
    //tempGX = gamma / 180 * 50;
    //tempGY = beta / 180 * 50;
    var hash = window.location.hash.replace('#', '');

    pageModel[hash].deviceorientation(param);
    //console.log('重力矢量方向', tempGX);
    this._lastGamma = gamma;
    this._lastBeta = beta;
  }
}
